<template>
  <div>
    <el-row v-if="list.length > 0">
      <div v-for="item in list" :key="item.index" class="check-div">
        <div v-if="item.fieldType == 'content'" style="margin-bottom: 20px">
          <el-checkbox
            v-if="item.type == '2'"
            v-model="checked[item.index]"
            :true-label="item.index"
            :false-label="''"
            :disabled="disabled"
            @change="checkBox"
          >
            {{ item.name }}
          </el-checkbox>
          <el-radio
            v-if="item.type == '1'"
            v-model="radio[item.groupIndex]"
            :label="item.index"
            :disabled="disabled"
            @change="checkRadio"
          >
            {{ item.name }}
          </el-radio>
        </div>
      </div>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'Check',
  model: {
    prop: 'value',
    event: 'dataEmit'
  },
  props: {
    list: {
      type: Array,
      default: () => []
    },
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      checked: {},
      radio: {}
    }
  },
  watch: {
    value() {
      this.getCheck()
    }
  },
  mounted() {},
  created() {
    this.getCheck()
    this.$emit('dataEmit', this.objToString())
  },
  methods: {
    getCheck() {
      let val = this.value
      if (this.value.indexOf('||') > -1) {
        val = this.value.split('||')[0]
      }
      if (val) {
        const arr = val.split(',')
        arr.forEach((el) => {
          this.list.forEach((item) => {
            if (item.index === el) {
              if (item.type === '1') {
                // this.radio[item.groupIndex] = el
                this.$set(this.radio, item.groupIndex, el)
              }
              if (item.type === '2') {
                this.$set(this.checked, item.index, el)
              }
            }
          })
        })
      }
    },
    objToString() {
      const arr = []
      let sum = ''
      for (const key in this.radio) {
        if (this.radio[key]) {
          arr.push(this.radio[key])
        }
      }
      for (const key in this.checked) {
        if (this.checked[key]) {
          arr.push(this.checked[key])
        }
      }
      arr.forEach((el) => {
        this.list.forEach((item) => {
          if (item.index === el && (item.score || item.score == 0)) {
            if (sum === '') {
              sum = item.score
            } else {
              sum += item.score
            }
          }
        })
      })
      if (sum !== '') {
        return arr.join(',') + '||' + sum
      } else {
        return arr.join(',')
      }
    },
    checkRadio() {
      this.$emit('dataEmit', this.objToString())
    },
    checkBox() {
      this.$emit('dataEmit', this.objToString())
    }
  }
}
</script>

<style scoped>
.check-div {
  float: left;
  margin-right: 30px;
}
</style>
